<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录系统</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f5f5f5;
        }

        .login-container {
            background-color: #fff;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }

        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 1.5rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #555;
            font-weight: 500;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
            box-sizing: border-box;
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: #4a90e2;
            box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
        }

        button {
            width: 100%;
            padding: 0.75rem;
            background-color: #4a90e2;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1rem;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #357abd;
        }

        .message {
            margin-top: 1rem;
            padding: 0.75rem;
            border-radius: 4px;
            text-align: center;
        }

        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>

<body>
    <div class="login-container">
        <h2>用户登录</h2>
        <form id="loginForm">
            <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" id="username" name="username" required>
            </div>
            <div class="form-group">
                <label for="password">密码:</label>
                <input type="text" id="password" name="password" required>
            </div>
            <button type="submit">登录</button>
        </form>
        <div id="message" class="message" style="display: none;"></div>
        <div class="test-accounts">
            <h3>测试账户</h3>
            <p>所有测试账户的密码均为：<strong>Abcd.123</strong></p>
            <ul>
                <li>demo1</li>
                <li>demo2</li>
                <li>demo3</li>
                <li>demo4</li>
                <li>demo5</li>
            </ul>
        </div>
    </div>

    <style>
        .test-accounts {
            margin-top: 1.5rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #4a90e2;
        }

        .test-accounts h3 {
            margin-top: 0;
            margin-bottom: 0.5rem;
            color: #4a90e2;
            font-size: 1rem;
        }

        .test-accounts p {
            margin-bottom: 0.5rem;
            color: #666;
            font-size: 0.9rem;
        }

        .test-accounts ul {
            margin: 0;
            padding-left: 1.5rem;
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .test-accounts li {
            color: #555;
            font-size: 0.9rem;
            padding: 0.25rem 0.5rem;
            background-color: #fff;
            border-radius: 3px;
            border: 1px solid #ddd;
            list-style-type: none;
            cursor: pointer;
            transition: all 0.2s ease;
            position: relative;
        }

        .test-accounts li:hover {
            background-color: #4a90e2;
            color: white;
            border-color: #4a90e2;
        }

        .test-accounts li.copied::after {
            content: '已复制!';
            position: absolute;
            right: -40px;
            top: 50%;
            transform: translateY(-50%);
            background-color: #4a90e2;
            color: white;
            padding: 0.2rem 0.5rem;
            border-radius: 3px;
            font-size: 0.8rem;
            white-space: nowrap;
        }
    </style>

    <script>
        // 为测试账户添加复制功能
        document.addEventListener('DOMContentLoaded', function () {
            const accountItems = document.querySelectorAll('.test-accounts li');
            accountItems.forEach(item => {
                item.addEventListener('click', function () {
                    const username = this.textContent;
                    navigator.clipboard.writeText(username)
                        .then(() => {
                            document.getElementById('username').value = username;
                            document.getElementById('password').value = 'Abcd.123';
                            document.getElementsByTagName('button')[0].click();
                        })
                        .catch(err => {
                            console.error('复制失败:', err);
                        });
                });
            });
        });
    </script>

    <!-- 引入哈希库 -->
    <script src="crypto/sha1.min.js"></script>
    <script src="crypto/sha256.min.js"></script>
    <script src="crypto/md5.min.js"></script>

    <!-- 引入密码编码器组件 -->
    <script src="password-encoder.js"></script>
    <script>

        // 预登录获取盐值
        function prelogin(username) {
            return fetch('http://localhost:8082/api/prelogin', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ loginName: username })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('预登录请求失败');
                }
                return response.json();
            });
        }

        // 登录函数
        function login(loginName, encryptedPassword) {
            return fetch('http://localhost:8082/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ loginName: loginName, passwd: encryptedPassword })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('登录请求失败');
                }
                return response.json();
            });
        }

        // 表单提交事件处理
        document.getElementById('loginForm').addEventListener('submit', async function (event) {
            event.preventDefault(); // 阻止表单默认提交

            // 获取表单数据
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const messageDiv = document.getElementById('message');
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;

            // 清空之前的消息
            messageDiv.style.display = 'none';

            try {
                // 显示加载状态
                submitButton.disabled = true;
                submitButton.textContent = '处理中...';

                // 第一步：预登录获取盐值
                submitButton.textContent = '验证用户信息...';
                const preloginResult = await prelogin(username);

                if (preloginResult.error !== 0) {
                    throw new Error(preloginResult.info || '预登录失败');
                }

                // 获取盐信息
                const { saltType, serverSalt, sessionSalt } = preloginResult;
                console.log('获取到的盐信息:', { saltType, serverSalt, sessionSalt });

                // 第二步：执行两次加密
                submitButton.textContent = '加密密码...';

                // 第一次加密：密码 + serverSalt
                const firstEncrypted = PasswordEncoder.hashBase64(password, serverSalt, saltType);
                console.log('第一次加密结果:', firstEncrypted);

                // 第二次加密：第一次加密结果 + sessionSalt
                const secondEncrypted = PasswordEncoder.hashBase64(firstEncrypted, sessionSalt, saltType);
                console.log('第二次加密结果:', secondEncrypted);

                // 使用URL安全格式
                const encryptedPassword = secondEncrypted;

                // 第三步：登录
                submitButton.textContent = '登录中...';
                const loginResult = await login(username, encryptedPassword);

                if (loginResult.error !== 0) {
                    throw new Error(loginResult.info || '登录失败');
                }

                // 登录成功
                messageDiv.textContent = "用户 " + username + "，" + (loginResult.info || '登录成功');
                messageDiv.className = 'message success';
                messageDiv.style.display = 'block';

                console.log('登录成功，用户:', loginResult.user);
                // 这里可以添加登录成功后的操作，如保存用户信息到localStorage或重定向

            } catch (error) {
                // 显示错误消息
                messageDiv.textContent = '登录失败: ' + (error.message || '未知错误');
                messageDiv.className = 'message error';
                messageDiv.style.display = 'block';
                console.error('登录错误:', error);
            } finally {
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.textContent = originalText;
            }
        });
    </script>
</body>

</html>